package com.niconicod.ofb.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.niconicod.ofb.PlayerPlaneInputProcessor;
import com.niconicod.ofb.actors.DebugBackground;
import com.niconicod.ofb.actors.PlayerPlane;

public class GameScreen implements Screen {

    public static final float WORLD_HEIGHT = 32;

    private Stage stage;
    private Viewport viewport;
    private World world;
    private Box2DDebugRenderer debugRenderer;
    private Sprite sprite;

    @Override
    public void show() {
        initStage();
        initPhysics();

        sprite = new Sprite(new Texture("MainPlane.png"));

//        PlayerPlane plane = PlayerPlane.getDummyInstance(sprite, new Vector2(8,8), new Vector2());

        PlayerPlane plane = PlayerPlane.createPhysicalInstance(sprite, new Vector2(4, 4), new Vector2(), world);
        stage.addActor(plane);
        stage.setKeyboardFocus(plane);

        stage.addActor(new DebugBackground());

        PlayerPlaneInputProcessor planeInputProcessor = new PlayerPlaneInputProcessor(plane);

        InputMultiplexer inputMultiplexer = new InputMultiplexer(planeInputProcessor, stage);

        Gdx.input.setInputProcessor(inputMultiplexer);
    }

    private void initStage() {
        float aspectRatio = (float) Gdx.graphics.getWidth() / Gdx.graphics.getHeight();

        viewport = new FitViewport(WORLD_HEIGHT * aspectRatio, WORLD_HEIGHT);
        stage = new Stage(viewport);
        stage.setDebugAll(true);
    }

    private void initPhysics() {
        world = new World(new Vector2(0, 0), true);
        debugRenderer = new Box2DDebugRenderer();
    }

    @Override
    public void render(float delta) {
        ScreenUtils.clear(0, 0, 1, 0);
        world.step(delta, 1, 1);
        stage.act(delta);
        stage.draw();
        debugRenderer.render(world, stage.getCamera().combined);
    }

    @Override
    public void resize(int width, int height) {
        viewport.update(width, height);
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();
    }

    private float getAspectRatio() {
        return (float) Gdx.graphics.getWidth() / Gdx.graphics.getHeight();
    }
}
